<template>
  <div class="bg-white border border-gray-200 rounded-lg p-6 shadow-sm">
    <!-- 材料类型标题 -->
    <div class="flex items-center justify-between mb-4">
      <div class="flex items-center space-x-3">
        <span class="text-2xl">{{ icon }}</span>
        <h3 class="text-lg font-medium text-gray-900">{{ title }}</h3>
      </div>
      <label class="flex items-center">
        <input
          type="checkbox"
          :checked="!!materialConfig"
          @change="toggleMaterial"
          class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
        >
        <span class="ml-2 text-sm text-gray-700">启用</span>
      </label>
    </div>

    <div v-if="materialConfig" class="space-y-4">
      <!-- 文件上传区域 -->
      <div class="mb-6">
        <FileUpload
          :material-type="getMaterialType()"
          :chapter-number="chapterNumber"
          :initial-files="materialConfig.uploadedFiles || []"
          @files-uploaded="handleFilesUploaded"
          @file-deleted="handleFileDeleted"
        />
      </div>



      <!-- 权重配置 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">权重分值</label>
        <div class="flex items-center space-x-4">
          <input
            v-model.number="materialConfig.weight"
            type="number"
            min="0"
            max="100"
            class="w-24 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
          <span class="text-sm text-gray-500">%</span>
          <div class="flex-1">
            <div class="w-full bg-gray-200 rounded-full h-2">
              <div 
                :class="`bg-${color}-500 h-2 rounded-full transition-all duration-300`"
                :style="{ width: `${Math.min(materialConfig.weight || 0, 100)}%` }"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 额外配置选项 -->
      <div v-if="showExtraOptions" class="space-y-3">
        <div class="flex items-center space-x-4">
          <label class="flex items-center">
            <input
              v-model="materialConfig.isRequired"
              type="checkbox"
              class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
            >
            <span class="ml-2 text-sm text-gray-700">必修</span>
          </label>
          <label class="flex items-center">
            <input
              v-model="materialConfig.allowDownload"
              type="checkbox"
              class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
            >
            <span class="ml-2 text-sm text-gray-700">允许下载</span>
          </label>
        </div>

        <!-- 时长配置（仅视频） -->
        <div v-if="title === '视频'">
          <label class="block text-sm font-medium text-gray-700 mb-2">预估时长（分钟）</label>
          <input
            v-model.number="materialConfig.duration"
            type="number"
            min="1"
            class="w-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="30"
          >
        </div>

        <!-- 截止时间配置（仅作业） -->
        <div v-if="title === '作业'">
          <label class="block text-sm font-medium text-gray-700 mb-2">截止时间</label>
          <input
            v-model="materialConfig.deadline"
            type="datetime-local"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
        </div>

        <!-- 描述 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">描述</label>
          <textarea
            v-model="materialConfig.description"
            rows="2"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            :placeholder="`请输入${title}的描述信息`"
          ></textarea>
        </div>
      </div>

      <!-- 展开/收起按钮 -->
      <button
        type="button"
        @click="showExtraOptions = !showExtraOptions"
        class="text-sm text-blue-600 hover:text-blue-800 flex items-center space-x-1"
      >
        <span>{{ showExtraOptions ? '收起' : '更多选项' }}</span>
        <svg 
          :class="{ 'rotate-180': showExtraOptions }"
          class="w-4 h-4 transition-transform duration-200" 
          fill="none" 
          stroke="currentColor" 
          viewBox="0 0 24 24"
        >
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
        </svg>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import FileUpload from './FileUpload.vue'

interface UploadedFile {
  filename: string
  originalName: string
  size: number
  url: string
  path: string
}

interface MaterialConfigType {
  weight: number
  isRequired?: boolean
  allowDownload?: boolean
  duration?: number
  deadline?: string
  description?: string
  uploadedFiles?: UploadedFile[]
}

interface Props {
  modelValue?: MaterialConfigType
  title: string
  icon: string
  color: string
  chapterNumber?: number
  materialType?: string
}

const props = withDefaults(defineProps<Props>(), {
  chapterNumber: 1
})
const emit = defineEmits(['update:modelValue'])

const materialConfig = ref<MaterialConfigType | undefined>(props.modelValue)
const showExtraOptions = ref(false)

// 用于控制是否应该触发更新事件的标志
const isInternalUpdate = ref(false)

// 监听配置变化并发射更新事件
watch(materialConfig, (newValue) => {
  // 如果是内部更新（如文件删除），则不触发emit，避免连锁反应
  if (!isInternalUpdate.value) {
    emit('update:modelValue', newValue)
  }
}, { deep: true })

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  materialConfig.value = newValue
}, { deep: true })

// 切换材料启用状态
const toggleMaterial = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.checked) {
    // 启用材料，创建默认配置
    materialConfig.value = {
      weight: getDefaultWeight(),
      isRequired: false,
      allowDownload: true,
      description: ''
    }
  } else {
    // 禁用材料
    materialConfig.value = undefined
  }
}



// 获取默认权重
const getDefaultWeight = () => {
  switch (props.title) {
    case '讲义': return 20
    case '课件': return 15
    case '视频': return 20
    case '示例材料': return 15
    case '实践课堂练习': return 15
    case '作业': return 15
    default: return 10
  }
}



// 获取材料类型
const getMaterialType = () => {
  // 如果传入了materialType属性，优先使用
  if (props.materialType) {
    return props.materialType
  }
  
  // 否则根据title映射
  switch (props.title) {
    case '讲义':
      return 'lecture'
    case '课件':
      return 'slides'
    case '视频':
      return 'video'
    case '示例材料':
      return 'examples'
    case '实践课堂练习':
      return 'practice'
    case '作业':
      return 'assignment'
    default:
      return 'lecture'
  }
}

// 处理文件上传成功
const handleFilesUploaded = (files: UploadedFile[]) => {
  if (materialConfig.value) {
    if (!materialConfig.value.uploadedFiles) {
      materialConfig.value.uploadedFiles = []
    }
    // 直接添加完整的文件信息
    materialConfig.value.uploadedFiles.push(...files)
    
    // 手动触发更新事件，确保父组件能收到最新的文件列表
    emit('update:modelValue', materialConfig.value)
  }
}

// 处理文件删除
const handleFileDeleted = (fileName: string) => {
  if (materialConfig.value?.uploadedFiles) {
    const index = materialConfig.value.uploadedFiles.findIndex(file => file.filename === fileName)
    if (index > -1) {
      // 标记为内部更新，避免触发深度监听器的emit
      isInternalUpdate.value = true
      
      // 删除文件
      materialConfig.value.uploadedFiles.splice(index, 1)
      
      // 使用nextTick确保DOM更新完成后再手动触发一次更新
      nextTick(() => {
        // 手动触发更新事件，确保父组件能收到最新的文件列表
        emit('update:modelValue', materialConfig.value)
        
        // 重新启用深度监听器
        isInternalUpdate.value = false
      })
    }
  }
}
</script>

<style scoped>
/* 组件特定样式 */
.rotate-180 {
  transform: rotate(180deg);
}
</style>